<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24" >
            <a-form-model-item label="模板名称" v-show="!isExecDevops"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateName">
              <div style="display: flex;">
                <a-input v-model="model.templateName" placeholder="请输入模板名称" ></a-input>
                <a-button @click="addMaintenanceContext" type="primary" style="margin-left: 10px;">添加保养内容</a-button>
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <div v-for="item in contexts" :key="item.id" style="border: 1px solid #ccc">
              <a-form-model-item label="保养名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateContext">
                <div style="display: flex;margin-top: 10px;">
                  <a-input v-model="item.name" placeholder="请输入保养名称"></a-input>
                  <!-- <a-tooltip context="删除当前保养内容" placement="top"> -->
                    <a-button style="margin-left: 20px;" v-show="contexts.length>1" @click="deleteCurrentMaintenanceContext(item)"  type="primary">-</a-button>
                  <!-- </a-tooltip> -->
                  
                </div>
                <a-button  @click="addDetail(item)" type="primary" style="margin-left: 10px; ">新增</a-button>
                <div v-for="detail in item.details" :key="detail.id" style="margin-top: 10px;">
                  
                <YksMaintenanceTemplateDetailForm :detail="detail" :item="item"
                 @reduceDetail="reduceDetail" @addControl="addControl" @deleteControl="deleteControl" :currentEquipmentId="currentEquipmentId"
                 ref="detailForm"></YksMaintenanceTemplateDetailForm>
              </div>
              </a-form-model-item>
            </div>
          </a-col>
          <!-- <a-col :span="24" >
            <a-form-model-item label="模板内容" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateContext">
              <a-input v-model="model.templateContext" placeholder="请输入模板内容" ></a-input>
            </a-form-model-item>
          </a-col> -->
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs" v-show="false">
      <a-tab-pane tab="保养模板明细表" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="yksMaintenanceTemplateDetailTable.loading"
          :columns="yksMaintenanceTemplateDetailTable.columns"
          :dataSource="yksMaintenanceTemplateDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue,randomUUID } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import YksMaintenanceTemplateDetailForm from './YksMaintenanceTemplateDetailForm.vue'
  import Tooltip from 'ant-design-vue/es/tooltip'


  export default {
    name: 'YksMaintenanceTemplateForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
      YksMaintenanceTemplateDetailForm,
      Tooltip
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        action:'',
        model:{
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           templateName: [
              { required: true, message: '请输入模板名称!'},
           ],
          //  templateContext: [
          //     { required: true, message: '请输入模板内容!'},
          //  ],
        },
        refKeys: ['yksMaintenanceTemplateDetail', ],
        tableKeys:['yksMaintenanceTemplateDetail', ],
        activeKey: 'yksMaintenanceTemplateDetail',
        // 保养模板明细表
        yksMaintenanceTemplateDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '名称',
              key: 'name',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '控件类型',
              key: 'controlType',
              type: JVXETypes.select,
              options:[],
              dictCode:"control_type",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '控件值',
              key: 'controlValue',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '触发类型',
              key: 'controlRequired',
              type: JVXETypes.select,
              options:[],
              dictCode:"",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:"是否必填",
            },
          ]
        },
        url: {
          add: "/dev/yksMaintenanceTemplate/add",
          edit: "/dev/yksMaintenanceTemplate/edit",
          queryById: "/dev/yksMaintenanceTemplate/queryById",
          yksMaintenanceTemplateDetail: {
            list: '/dev/yksMaintenanceTemplate/queryYksMaintenanceTemplateDetailByMainId'
          },
        },
        contexts: [
        // {
        //   id: 1,
        //   name: '日常保养',
        //   details: [
        //     {
        //       id: 1,
        //       controlType: '1',
        //       controlValue: '保养内容1',
        //       controlRequired: '1',
        //     },{
        //       id: 2,
        //       controlType: '1',
        //       controlValue: '保养内容3',
        //       controlRequired: '1',
        //     },
        //   ],
        // },
        // {
        //   id: 2,
        //   name: '日常保养1',
        //   details: [
        //     {
        //       id: 1,
        //       controlType: '1',
        //       controlValue: '保养内容2',
        //       controlRequired: '1',
        //     },
        //   ],
        // },
      ],
      deleteData:[],
      currentEquipmentId:'',
      isExecDevops:false
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      
    },
    created () {
    },
    methods: {
      addControl(item){
        debugger
        if(!item.controls){
          item.controls=[]
        }
        item.controls.push({
            id:randomUUID(),
            value:''
        })
      },
      deleteControl(item,control){
        debugger
        if(item.controls.length>1){
          for(var i=0;i<item.controls.length;i++){
          if(item.controls[i].id==control.id){
            item.controls.splice(i,1)
          }
        }
      }
    },
    refreshControl(item)
    {
      let controls=item.controls
      item.controls=[]
        for(var i=0;i<controls.length;i++){
          item.controls.push(controls[i])
        }
    },
      addMaintenanceContext() {
      console.log('新增模板')
      this.contexts.push({
         id:randomUUID(),
        name:'',
        extText:'context',
        details:[{
          id:randomUUID(),
          controlType:'1',
          controlValue:'',
          controlRequired:'1',
          controls:[{
            id:randomUUID(),
            value:''
          }]
        }]
      })
    },
    deleteCurrentMaintenanceContext(item){
      if(this.contexts.length>1){
        for(var i=0;i<this.contexts.length;i++){
          if(this.contexts[i].id==item.id){
            this.contexts.splice(i,1)
          }
        }
      }
    },
    addDetail(item) {
      debugger
      this.$nextTick(() => {
        item.details.push({
          id:randomUUID(),
          controlType:'1',
          controlValue:'',
          controlRequired:'1',
          controls:[{
            id:randomUUID(),
            value:''
          }]
        })
        })
        
        this.refreshContexts()
      },
      refreshContexts(){
  let contexts=this.contexts
        this.contexts=[]
        for(var i=0;i<contexts.length;i++){
          this.contexts.push(contexts[i])
        }
      },
      reduceDetail(item,detail){
        
        if(item.details.length>1){
          for(var i=0;i<item.details.length;i++){
          if(item.details[i].id==detail.id){
            item.details.splice(i,1)
          }
        }
        }
        this.refreshContexts()
        // let contexts=this.contexts
        // this.contexts=[]
        // for(var i=0;i<contexts.length;i++){
        //   this.contexts.push(contexts[i])
        // }
        
        
      },
      addBefore(){
        this.yksMaintenanceTemplateDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.yksMaintenanceTemplateDetail.list, params, this.yksMaintenanceTemplateDetailTable)
          this.loadDetailData(params)
        }
        else{
          if(!this.isExecDevops){
            this.model.equipmentId = this.currentEquipmentId
          }else{
            this.model.equipmentId=''
            this.model.templateName="运维执行临时数据"
            this.model.delFlag=1
          }
          this.addMaintenanceContext()
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        allValues=this.setFormDataFromPage(allValues)
        let main = Object.assign(this.model, allValues.formValue)
        
          return {
          ...main, // 展开
          yksMaintenanceTemplateDetailList: allValues.tablesValue[0].tableData,
        }
        
        
      },
      validateError(msg){
        this.$message.error(msg)
      },
      setFormDataFromPage(allValues){
        let name=''
        var guid = ''
        
        allValues.tablesValue[0].tableData=[]
        if(this.contexts.length>0){
          for(var i=0;i<this.contexts.length;i++){
            guid=randomUUID()
            name=name+this.contexts[i].name+","
            //明细数据
            var context={}
            context.name=this.contexts[i].name
            context.extText='context' //标记为内容明细
            context.extText1=guid      //同一个模板内容里面的guid相同
            allValues.tablesValue[0].tableData.push(context)
            for(var j=0;j<this.contexts[i].details.length;j++){
              var detail={}
              detail.name=this.contexts[i].details[j].name
              detail.extText='control' //标记为控件明细
              detail.controlType=this.contexts[i].details[j].controlType
              if(detail.controlType=='3'||detail.controlType=='4'){
                detail.controlValue=JSON.stringify(this.contexts[i].details[j].controls)
              }
              else{
                detail.controlValue=this.contexts[i].details[j].controlValue
              }
              if(detail.controlType=='6'){
                detail.extText2=this.contexts[i].details[j].productId
              }
              if(detail.controlType=='7'){
                detail.extText2=this.contexts[i].details[j].materialId
              }
              detail.controlRequired=this.contexts[i].details[j].controlRequired
              detail.extText1=guid      //同一个模板内容里面的guid相同
              allValues.tablesValue[0].tableData.push(detail)
            }
            // extText
          }
        }
        allValues.tablesValue[0].deleteData=this.deleteData
        allValues.formValue.templateContext=name.substring(0,name.length-1)
        return allValues
      },
      loadDetailData(params){
        
        getAction(this.url.yksMaintenanceTemplateDetail.list, params).then((res) => {
        if (res.success) {
          this.deleteData=res.result
          let listContexts =res.result.filter(p=>p.extText=='context')
          for(var i=0;i<listContexts.length;i++){
            let context={}
            context.id=listContexts[i].id
            context.name=listContexts[i].name
            context.extText=listContexts[i].extText
            context.extText1=listContexts[i].extText1
            this.contexts.push(context)
          }
          
          for(var i=0;i<this.contexts.length;i++){
            this.contexts[i].details=res.result.filter(p=>p.extText=='control'&&p.extText1==this.contexts[i].extText1)
            for(var j=0;j<this.contexts[i].details.length;j++){
              let detail=this.contexts[i].details[j]
              if(detail.controlType=='3'||detail.controlType=='4'){
                detail.controls=JSON.parse(detail.controlValue) 
                detail.controlValue=''
              }
              else{
                detail.controls=[]
                detail.controls.push({id:randomUUID(),value:''})
              }
            }
          }
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          // this.dataSource = res.result.records||res.result;
          // if(res.result.total)
          // {
          //   this.ipagination.total = res.result.total;
          // }else{
          //   this.ipagination.total = 0;
          // }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        }else{
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
      }

    }
  }
</script>

<style scoped>
</style>